var express = require('express');
var router = express.Router();

// var mongoClient = require("mongodb").mongoClient;
// var DB_CONN_STR = "mongodb://127.0.0.1:27017/test";
var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = 'mongodb://localhost:27017/test';

/* GET users listing. */
//该文件下的/指的是根目录，从app.js中传过来的/user----jw
      //app.use('/users', users);--------jw
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.post('/loginFile', function(req, res, next) {
  // console.log(req.body)
  //建立数据库的链接
  var email = req.body.email;
  var password = req.body.password;
  MongoClient.connect(DB_CONN_STR,(err,db)=>{
    //这里的db指的是数据库
    if(err){
      console.log(err);
    }else{
      console.log('connect success');
      var conn = db.collection("user");
      //对mongo表的操作命令
      var data = {email:email,password:password}
      conn.find(data).toArray((err,result)=>{
        if(result.length>0){
          req.session.email = result[0].email;
          res.redirect('/');
        }else{
          res.send("登陆失败")
        }
        db.close();
      });
    }
  })
});
router.get('/registerFile', function(req, res, next) {
  //将input中的值写入到数据库中
  var email = req.query.email;
  var password = req.query.password;
  MongoClient.connect(DB_CONN_STR,(err,db)=>{
    var conn = db.collection("user");
    var data = {email:email,password:password};
    conn.insert(data,(err,result)=>{
      if(err){
        res.send(err);
      }else{
        res.send("注册成功")
      }
      db.close();
    });

  })
});

module.exports = router;
